package com.leyou.controller;

import com.leyou.pojo.User;
import com.leyou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import javax.xml.bind.SchemaOutputResolver;


@Controller
public class UserController {
    @Autowired
    private UserService userService;


    @GetMapping("check/{data}/{type}")
    public ResponseEntity<Boolean> checkUserData(@PathVariable("data") String data,@PathVariable("type") Integer type){
        //要校验的数据类型：1，用户名；2，手机
        Boolean bol = this.userService.checkData(data,type);
        if(bol == null){
            return ResponseEntity.badRequest().build();//参数出错
        }
        return ResponseEntity.ok(bol);//判断结果，用户是否可用
    }


    /**
     * 发送验证代码
     *  get设置路径变量post设置请求参数，二者都是添加必要信息注意对应关系
     * @param phone 电话
     * @return {@link ResponseEntity}<{@link Void}>
     */
    @PostMapping("code")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone") String phone){
        this.userService.sendVerifyCode(phone);
        return ResponseEntity.status(HttpStatus.CREATED).build();//返回状态码
    }

    /**
     * 注册
     *  @Valid 校验对象的注解
     * @param user 用户
     * @param code 验证码码
     * @return {@link ResponseEntity}<{@link Void}>
     */
    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid User user, @RequestParam("code")String code){
        this.userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }


    /**
     * 查询用户
     *
     * @param username 用户名
     * @param password 密码
     * @return {@link ResponseEntity}<{@link User}>
     */
    @GetMapping("query")
    public ResponseEntity<User> queryUser(@RequestParam("username") String username,
                                          @RequestParam("password") String password){

        User user = this.userService.queryUser(username,password);

        if (user == null){
            return ResponseEntity.badRequest().build();//参数出错
        }
        return ResponseEntity.ok(user);
    }

}
